//
//  CYGDetailNaviBackView.m
//  CYGHuntForCity
//
//  Created by cygarm on 16/3/17.
//  Copyright © 2016年 cygarm. All rights reserved.
//

#import "CYGDetailNaviBackView.h"
#import <UIImageView+WebCache.h>

@interface CYGDetailNaviBackView () <UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIPageControl *pageCtrl;
@property (strong, nonatomic) NSArray<NSString *> *images;
@property (strong, nonatomic) NSMutableArray<UIImageView *> *imageViews;
@end

@implementation CYGDetailNaviBackView

- (void)awakeFromNib {
	
}

- (instancetype)initWithFrame:(CGRect)frame {
	if (self = [super initWithFrame:frame]) {
		self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil] lastObject];
		[self setupUI];
	}
	
	return self;
}

+ (instancetype)viewWithImages:(NSArray<NSString *> *)images {
	CYGDetailNaviBackView *view = [[self alloc] init];
	view.images = images;
	[view setupUI];
	
	return view;
}

- (void)setupUI {
	self.autoresizesSubviews = YES;
	self.scrollView.delegate = self;
	self.scrollView.bounces = NO;
	self.pageCtrl.currentPage = 0;
	self.pageCtrl.numberOfPages = self.images.count;
	[self setupImages];
}

- (void)setupImages {
	self.imageViews = [[NSMutableArray alloc] init];
	for (int i = 0; i < self.images.count; ++ i) {
		UIImageView *imgv = [[UIImageView alloc] init];
		[imgv sd_setImageWithURL:[NSURL URLWithString:self.images[i]] placeholderImage:[UIImage imageNamed:@"ContentViewNoImages"]];
		imgv.frame = CGRectMake(i*self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);
		imgv.contentMode = UIViewContentModeScaleToFill;
		[self.imageViews addObject:imgv];
		[self.scrollView addSubview:imgv];
	}	
	self.scrollView.contentSize = CGSizeMake(self.images.count*self.bounds.size.width, 0);
}

- (void)layoutSubviews {
	for (int i = 0; i < self.imageViews.count; ++ i) {
		self.imageViews[i].frame = CGRectMake(i*self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);;
	}
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
	CGFloat offsetX = scrollView.contentOffset.x;
	self.pageCtrl.currentPage = offsetX/self.bounds.size.width;
}

@end
